import { defineStore } from 'pinia'
import { getBookInfo } from '@/api/book'

export const useBookStore = defineStore(
  'bookStore',
  () => {
    const books = ref([]) // 书籍列表

    // 获取书籍列表
    function getBook(bookId) {
      const currentBook = books.value.find((book) => {
        return book.bookId == bookId
      })
      if (currentBook) {
        return Promise.resolve(currentBook)
      } else {
        return getBookInfo(bookId).then((apiRes) => {
          const bookInfo = apiRes.data
          books.value.push(bookInfo)
          return Promise.resolve(bookInfo)
        })
      }
    }

    return {
      getBook,
    }
  },
  { persist: true },
)
